<?php
class ContactPersonnelController  extends Zone_Action{
	public function indexAction(){
		$dep_id = getInt('dep_id',0);

		$user_id = get_user_id();
		$vars = array();
		$WHERE = array();
		$order_by = "ORDER BY `a`.`ID` DESC";

		$current_page = max(getInt('p',1),1);
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}

		if( isset($_REQUEST['rp'])){
			$vars['rp'] = $range_page;
		}
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";

		$field_order = array('name','depart_name','functions','birthday','phone');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;
			}
		}
		if($dep_id!=0){
			$vars['dep_id'] = $dep_id;
			$condition = " and `a`.`department_id`='$dep_id'";
			$titleDep = $this->Model->fetchRow("SELECT * FROM `departments` WHERE `ID`='$dep_id'");
			$this->view->titleDep = $titleDep['title'];
		}

		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total` FROM `personnels` as `a` WHERE `a`.`is_draft`='no' $condition");

		$posts = $this->Model->fetchAll("SELECT 
				`a`.*,
				`b`.`title` as `department_title`,
				`c`.`residence` as `address`
			FROM `personnels` as `a`
				LEFT JOIN `departments` as `b` 
					ON `b`.`ID`=`a`.`department_id`
				LEFT JOIN `personnels_cvs` as `c`
					ON `c`.`personnel_id`=`a`.`ID`	
			WHERE `a`.`is_draft`='no' 
				$condition $order_by $limit");

		$a = $vars;
		unset($a['p']);

		$page = page_ajax('#Contact/Personnel?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);

		$this->set(array(
			user_id =>get_user_id(),
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}
	
	public function viewAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`residence` as `address`,
				`a`.`functions` as `job_title`,
				`d`.`title` as `department_title`	
			FROM `personnels` as `a`
				LEFT JOIN `users` as `b`
					ON `a`.`updated_by_id`=`b`.`ID`
				LEFT JOIN `departments` as `d`
					ON `a`.`department_id`=`d`.`ID`
				LEFT JOIN `personnels_cvs` as `c`
					ON `c`.`personnel_id`=`a`.`ID`				
			WHERE 
				`a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");

		if( !$post ){
			return $this->setContent(error('Liên hệ không tồn tại hoặc đã bị xóa'));
		}
		
		$this->set(array(
			post => $post
		));	
	}	
}
?>